package web;

import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import objects.Board;
import objects.BoardData;
import objects.ConfigurationType;
import objects.Player;
import utils.FileHandler;

/**
 * Servlet implementation class CreateGameXml
 */
@MultipartConfig()
@WebServlet(name = "CreateGameXml", urlPatterns = {"/CreateGameXml"})
public class CreateGameXml extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateGameXml() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		if (!Board.getInstance().isGameInitialized() && !Board.getInstance().isGameStarted())
		{
			FileInputStream stream = null;
			
			try
			{
				// Get the file input stream from the component
				stream = (FileInputStream) request.getPart("file").getInputStream();
			
				// Try to read the file
				BoardData boardData = FileHandler.readXml(stream);
				
				boardData.setType(ConfigurationType.XML);
				// Set the board data
				Board.getInstance().setBdGameData(boardData);
				
				for (Player player : boardData.getPlayers()) 
		    	{
					// Enter the player to the room number roomNumber
					Board.getInstance().getRooms()[0].participantEnter(player);
					player.setRoomNumber(0);
				}

				Board.getInstance().backUp();
				
				request.setAttribute("creator", true);
				request.setAttribute("pageName", "newGame"); 
		    	// Call index.jsp (the page to call was set by pageName on the jsp)
		    	RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
		    	dispatcher.forward(request, response);
			  } catch (SAXException ex) {
				  request.setAttribute("errorMsg", "File is not a xml file");
				  request.setAttribute("pageName", "newGame"); 
		    	  // Call index.jsp (the page to call was set by pageName on the jsp)
		    	  RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
		    	  dispatcher.forward(request, response);
	          } catch (IOException ex) {
	              request.setAttribute("errorMsg", "IO exception occured");
	              request.setAttribute("pageName", "newGame"); 
		    	  // Call index.jsp (the page to call was set by pageName on the jsp)
		    	  RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
		    	  dispatcher.forward(request, response);
	          } catch (ParserConfigurationException ex) {
	              request.setAttribute("errorMsg", "Parse error occured");
	              request.setAttribute("pageName", "newGame"); 
		    	  // Call index.jsp (the page to call was set by pageName on the jsp)
		    	  RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
		    	  dispatcher.forward(request, response);
	          }
			  catch (ClassCastException ex) {
				  request.setAttribute("errorMsg", "File is not a xml file");
				  request.setAttribute("pageName", "newGame"); 
		    	  // Call index.jsp (the page to call was set by pageName on the jsp)
		    	  RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
		    	  dispatcher.forward(request, response);
			  }
			  catch (Exception e)
			  {
				request.setAttribute("errorMsg", e.getMessage());
				request.setAttribute("pageName", "newGame"); 
		    	// Call index.jsp (the page to call was set by pageName on the jsp)
		    	RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
		    	dispatcher.forward(request, response);
			  }
		}
		else
		{
			request.setAttribute("pageName", "errorPage"); 
	    	// Call index.jsp (the page to call was set by pageName on the jsp)
	    	RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
	    	dispatcher.forward(request, response);
		}
	}

}
